<template>
  <div class="mock-example">
    <h1>MockJS 数据示例</h1>
    
    <!-- 登录演示 -->
    <section class="section">
      <h2>1. 登录演示</h2>
      <div class="login-form">
        <input v-model="loginForm.username" type="text" placeholder="用户名" />
        <input v-model="loginForm.password" type="password" placeholder="密码" />
        <button @click="handleLogin" :disabled="isLoading">
          {{ isLoading ? '登录中...' : '登录' }}
        </button>
        <div class="tip">提示：可用账号 admin/123456 或 user/123456</div>
      </div>
      
      <div v-if="loginResult" class="result">
        <h3>登录结果：</h3>
        <pre>{{ loginResult }}</pre>
      </div>
    </section>

    <!-- 用户列表演示 -->
    <section class="section">
      <h2>2. 用户列表演示</h2>
      <div class="pagination-controls">
        <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
        <span>第 {{ currentPage }} 页</span>
        <button @click="nextPage">下一页</button>
      </div>
      <button @click="fetchUsers" :disabled="isLoading">
        {{ isLoading ? '加载中...' : '获取用户列表' }}
      </button>
      
      <div v-if="users.length > 0" class="user-list">
        <h3>用户列表 (共 {{ totalUsers }} 条):</h3>
        <div v-for="user in users" :key="user.id" class="user-item">
          <img :src="user.avatar" alt="{{ user.name }}" class="user-avatar" />
          <div class="user-info">
            <div class="user-name">{{ user.name }}</div>
            <div class="user-detail">年龄：{{ user.age }} | 角色：{{ user.role }}</div>
            <div class="user-detail">邮箱：{{ user.email }} | 电话：{{ user.phone }}</div>
            <div class="user-detail">状态：{{ user.status }} | 创建时间：{{ user.createTime }}</div>
          </div>
        </div>
      </div>
    </section>

    <!-- 产品列表演示 -->
    <section class="section">
      <h2>3. 产品列表演示</h2>
      <button @click="fetchProducts" :disabled="isLoading">
        {{ isLoading ? '加载中...' : '获取产品列表' }}
      </button>
      
      <div v-if="products.length > 0" class="product-list">
        <h3>产品列表 (前 3 个):</h3>
        <div v-for="product in products.slice(0, 3)" :key="product.id" class="product-item">
          <img :src="product.coverImage" alt="{{ product.name }}" class="product-image" />
          <div class="product-info">
            <div class="product-name">{{ product.name }}</div>
            <div class="product-price">价格：¥{{ product.price }}</div>
            <div class="product-stock">库存：{{ product.stock }} | 销量：{{ product.sales }}</div>
          </div>
        </div>
      </div>
    </section>

    <!-- 错误和延迟演示 -->
    <section class="section">
      <h2>4. 特殊场景演示</h2>
      <button @click="testError" :disabled="isLoading">测试错误响应</button>
      <button @click="testDelay" :disabled="isLoading">测试延迟响应 (2秒)</button>
      
      <div v-if="specialResult" class="result">
        <h3>响应结果：</h3>
        <pre>{{ specialResult }}</pre>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { login, getUsers, getError, getDelay } from '../api/user'
import { getProducts } from '../api/product'
import type { LoginResponseData } from '../types'

// 登录相关数据
const loginForm = ref({
  username: 'admin',
  password: '123456'
})
const loginResult = ref<any>(null)

// 用户列表相关数据
const users = ref<any[]>([])
const totalUsers = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)

// 产品列表相关数据
const products = ref<any[]>([])

// 特殊场景结果
const specialResult = ref<any>(null)

// 加载状态
const isLoading = ref(false)

// 登录处理
const handleLogin = async () => {
  isLoading.value = true
  try {
    const response = await login(loginForm.value.username, loginForm.value.password)
    loginResult.value = response.data
    console.log('登录成功:', response.data)
  } catch (error) {
    loginResult.value = error
    console.error('登录失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 获取用户列表
const fetchUsers = async () => {
  isLoading.value = true
  try {
    const response = await getUsers(currentPage.value, pageSize.value)
    // 修复响应数据访问路径
    if (response.data && response.data.data && response.data.data.list) {
      users.value = response.data.data.list
      totalUsers.value = response.data.data.total
    } else {
      // 如果结构不一致，尝试直接使用响应数据
      users.value = response.data?.list || []
      totalUsers.value = response.data?.total || 0
    }
    console.log('用户列表:', response.data)
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 获取产品列表
const fetchProducts = async () => {
  isLoading.value = true
  try {
    const response = await getProducts(1, 10)
    // 修复响应数据访问路径
    if (response.data && response.data.data && response.data.data.list) {
      products.value = response.data.data.list
    } else {
      // 如果结构不一致，尝试直接使用响应数据
      products.value = response.data?.list || []
    }
    console.log('产品列表:', response.data)
  } catch (error) {
    console.error('获取产品列表失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 测试错误响应
const testError = async () => {
  isLoading.value = true
  try {
    const response = await getError()
    specialResult.value = response.data
  } catch (error) {
    specialResult.value = error
    console.error('测试错误响应:', error)
  } finally {
    isLoading.value = false
  }
}

// 测试延迟响应
const testDelay = async () => {
  isLoading.value = true
  try {
    const response = await getDelay()
    specialResult.value = response.data
    console.log('延迟响应结果:', response.data)
  } catch (error) {
    specialResult.value = error
    console.error('测试延迟响应失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 分页控制
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    fetchUsers()
  }
}

const nextPage = () => {
  currentPage.value++
  fetchUsers()
}

// 使用 onMounted 生命周期钩子代替 DOMContentLoaded
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.mock-example {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.section {
  margin-bottom: 40px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

h1, h2, h3 {
  color: #333;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-width: 300px;
  margin-bottom: 20px;
}

input {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  padding: 10px 15px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover:not(:disabled) {
  background-color: #3aa876;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.tip {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.result {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.result pre {
  white-space: pre-wrap;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.user-list, .product-list {
  margin-top: 20px;
}

.user-item, .product-item {
  display: flex;
  gap: 15px;
  background-color: #fff;
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
}

.product-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
}

.user-info, .product-info {
  flex: 1;
}

.user-name, .product-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.user-detail, .product-price, .product-stock {
  font-size: 14px;
  color: #666;
  margin-bottom: 2px;
}
</style>